//
//  SJDetailViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/25.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "SJDetailViewController.h"
#import "SJBuyView.h"
#import "SubmitOrderViewController.h"
#import "PicTextViewController.h"
#import "JiaQianImageView.h"
#import "ReChargeViewController.h"

@interface SJDetailViewController ()<UIAlertViewDelegate>
{
    UIView *baseView;
    AlertV *tipsView;
    NSString *deal_by;
    NSInteger page;
    BOOL end;
    UIView *aView;
    SJBuyView *buyView;
    NSDateFormatter *formatter;
    NSUInteger buyer_count;
    NSString *up_users;
    BOOL buySuccess;
}
@property (nonatomic, strong) NSTimer *priceTimer;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *buyerArray;
@property (nonatomic, strong) NSTimer *getDataTimer;
@property (nonatomic, strong) NSMutableArray *jiaQArr;

@end

@implementation SJDetailViewController

- (void)loadView
{
    buyView = [[SJBuyView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = buyView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    buySuccess = NO;
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    [self addSubViews];
    [self setUpData];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [self.getDataTimer invalidate];
    [self.priceTimer invalidate];
}

- (void)viewDidAppear:(BOOL)animated
{
    [self getBuyPriceList:self.getDataTimer];
    self.getDataTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(getBuyPriceList:) userInfo:nil repeats:YES];
//    [NSThread detachNewThreadSelector:@selector(startTimer) toTarget:self withObject:nil];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self startTimer];
    });
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)buyerArray
{
    if (!_buyerArray) {
        _buyerArray = [NSMutableArray array];
    }
    return _buyerArray;
}

- (NSMutableArray *)jiaQArr
{
    if (!_jiaQArr) {
        _jiaQArr = [NSMutableArray array];
        for (int i = 0; i < 10; i++) {
            JiaQianImageView *view = [[JiaQianImageView alloc] init];
            [_jiaQArr addObject:view];
        }
    }
    return _jiaQArr;
}

- (void)setPrice:(CGFloat)price
{
    _price = price;
    [self performSelectorOnMainThread:@selector(handleWithPrice) withObject:nil waitUntilDone:YES];
}

- (void)handleWithPrice
{
    buyView.numView.number = [NSString stringWithFormat:@"%.1f", _price];
}

// 刷新价签
- (void)refreshUI
{
   __block BOOL alreadyRemove = NO;
    if (_buyerArray.count > 0) {
        if (!alreadyRemove) {
            [UIView animateWithDuration:2.0f animations:^{
                [self changeUI];
                alreadyRemove = YES;
            }];
        } else {
            [self changeUI];
        }
    }
    if (_buyerArray.count > 10) {
        [_buyerArray subarrayWithRange:NSMakeRange(0, 10)];
    }
    for (int i = 0; i < _buyerArray.count; i++) {
        BuyerModel *model = _buyerArray[i];
        JiaQianImageView *jiaV = self.jiaQArr[i];
        if (jiaV.flag == YES) {
          //  continue;
        }
        if (i < 5) {
            // 在左边加载价签
            jiaV.frame = CGRectMake(15, (15 + (buyView.leftPriceList.height - 80) / 5) * i + 25, buyView.leftPriceList.width - 60, 16);
            [buyView.leftPriceList addSubview:jiaV];
            // NSLog(@"y==%f, x==%f", jiaV.frame.origin.y, jiaV.frame.origin.x);
            jiaV.flag = YES;
        } else {
            // 右边
            jiaV.frame = CGRectMake(15, (15 + (buyView.rightPriceList.height - 75 ) / 5) * (i - 5) + 25, buyView.rightPriceList.width - 60, 16);
            [buyView.rightPriceList addSubview:jiaV];
            jiaV.flag = YES;
        }
        jiaV.user_nameLb.text = model.nickname;
        jiaV.numImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d", i + 1]];
        jiaV.priceLb.text = model.buy_price;
        /**
         *  0-正在付款
         *  1-正常等待付款
         *  2-失败(前面的人买了我就失败了)
         *  3-成交代发货
         *  4 已发货待收货
         *  5 已收货代晒单
         *  6已晒单彻底完成
         *  7违规，下单了，不付款
         *  8-用户单方面删除订单了
         *  11-付款时已超时
         */
        if ([model.status isEqualToString:@"1"]) {
            jiaV.statusImage.image = [UIImage imageNamed:@"waiting"];
        } else if ([model.status isEqualToString:@"0"] || [model.status isEqualToString:@"3"]) {
            jiaV.statusImage.image = [UIImage imageNamed:@"daifukuan"];
            if ([model.status isEqualToString:@"3"]){
                buySuccess =YES;
                for (UIView *view in [buyView.leftPriceList subviews]) {
                    if (view==jiaV) {
                        continue;
                    }
                    [view removeFromSuperview];
                }
                for (UIView *view in [buyView.rightPriceList subviews]) {
                    if (view==jiaV) {
                        continue;
                    }
                    [view removeFromSuperview];
                }
                [self.getDataTimer invalidate];
                [self.priceTimer invalidate];
                jiaV.user_nameLb.hidden = YES;
                jiaV.statusImage.hidden = YES;
                NSLog(@"aniamate qian -- %lf %lf",jiaV.left,jiaV.top);
                [UIView animateWithDuration:3.0f animations:^{
                    //[jiaV bringSubviewToFront:buyView];
                    //jiaV.user_nameLb.alpha = 0;
                    NSInteger integerX;
                    if (kScreenWidth>=320&&kScreenWidth<375) {
                        integerX = kScreenWidth/2 - 56*2-16*2;
                    }else if(kScreenWidth>=375&&kScreenWidth<414){
                        integerX = kScreenWidth/2 - 56*2;

                    }else{
                        integerX = kScreenWidth/2 - 56 - 16*2;
                    }
                    jiaV.center = CGPointMake(integerX, buyView.leftPriceList.height/2);
                    jiaV.transform = CGAffineTransformScale(jiaV.transform, 2.5, 2.5);
                    //jiaV.width=(buyView.leftPriceList.width - 60)*3;
                    //jiaV.height= 16*3;
                    //jiaV.frame.size=CGSizeMake((buyView.leftPriceList.width - 60)*3, 16*3);
                    
                } completion:^(BOOL finished) {
                    UILabel *useNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, (buyView.height-70 * kWidthScale-(buyView.leftPriceList.height-jiaV.frame.origin.y) - 50), kScreenWidth, 50)];
                    NSString *buySuccessStr=[NSString stringWithFormat:@"恭喜用户%@成交",model.nickname];
                    useNameLabel.text=buySuccessStr;
                    useNameLabel.textColor = kColors(218, 166, 46, 1);
                    useNameLabel.font = [UIFont systemFontOfSize:18];
                    useNameLabel.textAlignment = NSTextAlignmentCenter;
                    [buyView addSubview:useNameLabel];
                    UILabel *originalPriceLable = [[UILabel alloc]initWithFrame:CGRectMake(0, buyView.height-(buyView.leftPriceList.height-jiaV.bottom)-70 * kWidthScale, kScreenWidth, 50)];
                    originalPriceLable.textColor = [UIColor blackColor];
                    originalPriceLable.font = [UIFont systemFontOfSize:16];
                    originalPriceLable.textAlignment = NSTextAlignmentCenter;
                    originalPriceLable.text = [NSString stringWithFormat:@"获得原价%@的商品",self.model.original_price];
                    NSLog(@"aniamate hou -- %lf %lf",jiaV.left,jiaV.top);
                    NSLog(@"%lf %lf",originalPriceLable.frame.origin.x,originalPriceLable.frame.origin.y);
                    [buyView addSubview:originalPriceLable];
                    if (finished) {
                        baseView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
                        baseView.backgroundColor = [UIColor grayColor];
                        baseView.alpha = 0.5;
                        [self.view.window addSubview:baseView];
                        aView = [[UIView alloc] initWithFrame:CGRectMake(13, (kScreenHeight - 150) / 2, kScreenWidth - 26, 150)];
                        [self.view.window addSubview:aView];
                        aView.backgroundColor = [UIColor whiteColor];
                        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(22, 10, aView.width - 44, 50)];
                        [aView addSubview:title];
                        title.numberOfLines = 0;
                        if ([model.user_id isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]]) {
                            title.text = @"恭喜您成功购买了此商品, 60s后此活动结束!";
                        } else {
                            title.text = @"已经有用户成功购买了此商品, 60s后此活动结束!";
                        }
                        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
                        button.frame = CGRectMake((aView.width - 95) / 2, aView.height - 46, 95, 29);
                        [aView addSubview:button];
                        button.layer.cornerRadius = 5;
                        button.backgroundColor = kColors(218, 166, 46, 1);
                        aView.layer.cornerRadius = 5;
                        [button addTarget:self action:@selector(ensure:) forControlEvents:(UIControlEventTouchUpInside)];
                        [button setTitle:@"确定" forState:(UIControlStateNormal)];
                        button.titleLabel.font = [UIFont systemFontOfSize:12];
                        [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(actionEnd) userInfo:nil repeats:NO];
                    }
                }];
                end = YES;
                self.endblock(end);
                return;
            }

        } else {
            jiaV.statusImage.image = [UIImage imageNamed:@"time_out"];
            NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:model.buy_price];
            [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, model.buy_price.length)];
            [attri addAttribute:NSStrikethroughColorAttributeName value:kColors(255, 1, 1, 1) range:NSMakeRange(0, model.buy_price.length)];
            [jiaV.priceLb setAttributedText:attri];
        }
    }
}

- (void)changeUI
{
    buyView.bgView.backgroundColor = self.view.backgroundColor;
    buyView.bgView.frame = CGRectMake(buyView.imageView.left - 70, buyView.imageView.center.y - 30, 80, 80);
    buyView.lable0.frame = CGRectMake(0, 5, buyView.bgView.width, 20);
    buyView.lable0.font = [UIFont systemFontOfSize:20.0f];
    buyView.lable0.textColor = [UIColor blackColor];
    buyView.orginalPrice.frame = CGRectMake(0, buyView.lable0.bottom + 10, buyView.bgView.width, 20);
    buyView.orginalPrice.font = [UIFont systemFontOfSize:20.0f];
    buyView.orginalPrice.textColor = [UIColor blackColor];
}

- (void)actionEnd
{
    [baseView removeFromSuperview];
    [aView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)ensure:(UIButton *)button
{
    [baseView removeFromSuperview];
    [aView removeFromSuperview];
}

- (void)addSubViews
{
    self.title = @"速降详情";
    buyView.orginalPrice.text = self.model.original_price;
    
    [buyView.imageView sd_setImageWithURL:[NSURL URLWithString:self.model.head_img_url] placeholderImage:[UIImage imageNamed:@"tu-zhong02"]];
    buyView.userCount.text = [NSString stringWithFormat:@"%@人", self.model.up_users];
    [buyView.buyBtn addTarget:self action:@selector(actionBuybtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [buyView.clickBtn addTarget:self action:@selector(actionSeeDetail:) forControlEvents:(UIControlEventTouchUpInside)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionSeeDetail)];
    [buyView.imageView addGestureRecognizer:tap];
//    [buyView.coolBtn addTarget:self action:@selector(actionZanBtn:) forControlEvents:(UIControlEventTouchUpInside)];
//    [buyView.waitBtn addTarget:self action:@selector(actionWaiting:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)setUpData
{
    [NetworkHandle getDataWithUrl:[NSString stringWithFormat:@"%@%@",kBaseUrl, kDetailUrl] dictionary:@{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"page":[NSNumber numberWithInteger:page]} success:^(NSDictionary *dictionary) {
        if (dictionary[@"current"] != nil && [dictionary[@"current"] count] != 0) {
            [self.model setValuesForKeysWithDictionary:dictionary[@"current"]];
            if (self.model.period_id == nil) {
                [Tools showAlert:@"本期已结束,谢谢您的参与!"];
                [self.navigationController popToRootViewControllerAnimated:YES];
                return;
            } else {
                buyView.orginalPrice.text = self.model.original_price;
                buyView.nameLb.text = self.model.name;
                buyView.numView.number = self.model.current_price;
            }
        }
    }];
}

- (void)footerRefresh
{
    if (end) {
        [Tools showAlert:@"本场已结束!"];
        return;
    }
    page++;
    [self setUpData];
}

- (void)headerRefresh
{
    if (end) {
        [Tools showAlert:@"本场已结束!"];
        return;
    }
    page = 1;
    [self setUpData];
}

- (void)startTimer
{
    self.priceTimer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(actionChangePrice:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count > 0) {
        return self.dataArray.count;
    }
    return 0;
}

#pragma mark -- 点击事件

// 点击轮播图
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    [self actionSeeDetail:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 && [alertView.title isEqualToString:@"确认"]) {
       [self actionNoAlert];
    }
}

- (void)actionNoAlert
{
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kDealCheck];
    NSDictionary *dict0 = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"period_id":self.model.period_id};
    [NetworkHandle addToWindow];
    [NetworkHandle getInfoWithUrl:string dictionary:dict0 success:^(NSDictionary *dictionary) {
        [NetworkHandle removeFromWindow];
        if ([dictionary[@"code"] integerValue] == 200) {
            NSDictionary *data = dictionary[@"data"];
            NSLog(@"test --- %@",data);
            if ([data[@"user_already_make_a_deal"] integerValue] == 1) {
                NSDictionary *dict1 = @{@"commodity_id":self.model.commodity_id, @"period_id":self.model.period_id, @"price":[NSNumber numberWithFloat:self.price], @"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_by":@"1"};
                NSString *stringUrl = [NSString stringWithFormat:@"%@%@", kBaseUrl, kDealOrder];
                [self getinfoWith:stringUrl dict:dict1];
            } else {
                if ([data[@"deal_ticket_num"] integerValue] > 0) {
                    deal_by = @"1";
                    [self ensureBuyNow];
                } else {
                    if ([data[@"wallet"] floatValue] >= 20.0) {
                        deal_by = @"2";
                        [self ensureBuyNow];
                    } else {
                        // 没钱没券
                        [self creatAlert:@"您的订金余额不足,请及时充值!" imageName:@"qwcz" tag:3];
                    }
                }
            }
        } else {
            [Tools showAlert:dictionary[@"message"]];
        }
    }];
}

- (void)actionSeeDetail:(UIButton *)button
{
    // 点击图片进去详情
    PicTextViewController *picTexVC = [[PicTextViewController alloc] init];
    picTexVC.webUrl = self.model.detail_url;
    [self.navigationController pushViewController:picTexVC animated:YES];
}

- (void)actionSeeDetail
{
    [self actionSeeDetail:nil];
}

- (void)actionBuybtn:(UIButton *)button
{
    if (end) {
        [Tools showAlert:@"本场已结束!"];
        return;
    }
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    if ([app.PModel.showAlert isEqualToString:@"0"]) {
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确认" message:@"亲，确认拍下后，您有且只有60秒来完成支付! 为防止乱出价，如果在您支付的6o秒时间窗口内未能支付成功，您的20元定金券或等值余额将会被扣除，并在接下来的一小时不能出价。 如有人在您前面拍下（你处于排队等待支付状态），并在60秒成功支付，你的定金券或等值余额将返还到你的账户。您确定拍下么？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alertV show];
    }
}

- (void)creatAlert:(NSString *)string imageName:(NSString *)imageName1 tag:(NSInteger)tag
{
    baseView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    baseView.backgroundColor = [UIColor grayColor];
    baseView.alpha = 0.5;
    [self.view.window addSubview:baseView];
    tipsView = [[AlertV alloc] initWithFrame:CGRectMake(13, kScreenHeight / 2 - 125, kScreenWidth - 26, 125)];
    [self.view.window addSubview:tipsView];
    [tipsView.gotoCZBtn addTarget:self action:@selector(gotoChongZhi:) forControlEvents:(UIControlEventTouchUpInside)];
    [tipsView.gotoCZBtn setBackgroundImage:[UIImage imageNamed:imageName1] forState:(UIControlStateNormal)];
    tipsView.gotoCZBtn.tag = tag;
    [tipsView.ignoreBtn setBackgroundImage:[UIImage imageNamed:@"dcl"] forState:(UIControlStateNormal)];
    [tipsView.ignoreBtn addTarget:self action:@selector(ignore:) forControlEvents:(UIControlEventTouchUpInside)];
    tipsView.titleLb.text = string;
}

- (void)gotoChongZhi:(UIButton *)button
{
    [tipsView removeFromSuperview];
    [baseView removeFromSuperview];
    if (button.tag == 1 || button.tag == 2) {
        [self ensureBuyNow];
    } else {
        ReChargeViewController *rechVC = [[ReChargeViewController alloc] initWithNibName:@"ReChargeViewController" bundle:nil];
        [self.navigationController pushViewController:rechVC animated:YES];
    }
}

- (void)ensureBuyNow
{
    NSString *str = [NSString stringWithFormat:@"%@%@", kBaseUrl, kDealOrder];
    NSDictionary *dict1 = @{@"commodity_id":self.model.commodity_id, @"period_id":self.model.period_id, @"price":[NSNumber numberWithFloat:self.price], @"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_by":deal_by};
    [self getinfoWith:str dict:dict1];
}

- (void)getinfoWith:(NSString *)url dict:(NSDictionary *)dict
{
    [NetworkHandle getInfoWithUrl:url dictionary:dict success:^(NSDictionary *dictionary) {
        if ([dictionary[@"code"] integerValue] == 200) {
            SubmitOrderViewController *submitVC = [[SubmitOrderViewController alloc] initWithNibName:@"SubmitOrderViewController" bundle:nil];
            submitVC.dataDic = [NSDictionary dictionaryWithDictionary:dictionary[@"data"]];
            submitVC.goodImage = self.image;
            submitVC.period_id = self.model.period_id;
            [self.navigationController pushViewController:submitVC animated:YES];
        } else {
            [Tools showAlert:dictionary[@"message"]];
        }
    }];
}

- (void)ignore:(UIButton *)button
{
    [tipsView removeFromSuperview];
    [baseView removeFromSuperview];
}

- (void)lableText:(UILabel *)lable
{
    if (lable.text.length == 1) {
        lable.text = [NSString stringWithFormat:@"0%@", lable.text];
    }
}

- (void)actionChangePrice:(NSTimer *)timer
{
    if (self.price <= 0) {
        [self.priceTimer invalidate];
        self.price = 0.0f;
        return;
    }
    NSDate *endDate = [formatter dateFromString:self.model.end_time];
    NSTimeInterval endT = [endDate timeIntervalSince1970] - self.deviation;
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval start = [[formatter dateFromString:self.model.start_time] timeIntervalSince1970];
    self.price = self.model.original_price.floatValue * (endT - now) / (endT - start);
}

- (void)getBuyPriceList:(NSTimer *)timer3
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=current_period_buy_list"];
    NSDictionary *diction = @{@"period_id":self.model.period_id};
    NSMutableDictionary *signDict = [NSMutableDictionary dictionaryWithDictionary:diction];
    [signDict setValue:[Tools signDict:diction] forKey:@"sign"];
    [manager POST:url parameters:signDict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dict = responseObject;
        NSDictionary *dictionary = dict[@"data"];
        NSArray *array = dictionary[@"list"];
        up_users = dictionary[@"up_user"];
        [self.buyerArray removeAllObjects];
        for (NSDictionary *dic in array) {
            BuyerModel *model = [[BuyerModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.buyerArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            buyView.userCount.text = [NSString stringWithFormat:@"%@人", up_users];
//            if (_buyerArray.count == buyer_count && !buySuccess) {
//                [self refreshUI];
//                return; // 说明没有新的出价而且也没有人购买成功
//            } else {
//                [self refreshUI];
//            }
            if (buySuccess) {
                return;
            }else{
                [self refreshUI];
            }

        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
